package net.maku.module.controller;


import com.aliyuncs.utils.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.common.utils.Result;
import net.maku.framework.security.user.SecurityUser;
import net.maku.module.entity.AgCategoryEntity;
import net.maku.module.query.AgCategoryQuery;
import net.maku.module.service.AgCategoryService;
import net.maku.module.vo.AgCategoryVO;
import net.maku.storage.service.StorageService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/new/category")
@Tag(name = "栏目管理")
@AllArgsConstructor
public class AgCategoryController {

    private final StorageService storageService;
    @Resource
    private AgCategoryService categoryService;


    @Operation(summary = "查询栏目")
    @PostMapping("/getCategoryList")
//    @PreAuthorize("hasAuthority('member:user:all')")
    public Result<PageResult<AgCategoryVO>> getCategoryList(@RequestBody AgCategoryQuery query) {
        PageResult<AgCategoryVO> page = categoryService.getCategoryList(query);
        return Result.ok(page);
    }

    @Operation(summary = "根据角色查询栏目")
    @GetMapping("/getCategoryListByUser")
    public Result<PageResult<AgCategoryVO>> getCategoryListByUser(@RequestParam Integer websiteId,
                                                                  @RequestParam Integer pageNum,
                                                                  @RequestParam Integer pageSize,@RequestParam(required = false) String approveState) {
        if (SecurityUser.getUser() == null)
            return Result.error(403, "未登录，权限认证失败");
        long executor = SecurityUser.getUser().getId();
        return categoryService.getCategoryListByUser(websiteId, executor, pageNum, pageSize,approveState);
    }



    @Operation(summary = "新增栏目")
    @PostMapping("/addCategoryList")
    public Result<PageResult<AgCategoryVO>> addCategoryList(@RequestBody AgCategoryVO vo) {
        categoryService.addCategoryList(vo);
        return Result.ok();
    }


    @Operation(summary = "更改栏目")
    @PostMapping("/updateCategoryList")
    public Result<String> updateCategoryList(@RequestBody @Valid AgCategoryVO vo) {
        categoryService.updateCategoryList(vo);

        return Result.ok();
    }

    @Operation(summary = "删除栏目")
    @PostMapping("/deleteCategoryList")
    public Result<String> deleteCategoryList(@RequestBody List<Long> idList) {
        categoryService.deleteCategoryList(idList);

        return Result.ok();
    }

    @Operation(summary = "根据网站id获取栏目层级（分页）")
    @GetMapping("/getAllCategory")
    public Result<PageResult<AgCategoryVO>> getAllCategory(
            @RequestParam Integer websiteId,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize) {

        // 获取分页后的栏目数据
        return categoryService.getCategoriesByWebsiteId(websiteId, pageNum, pageSize);
    }

    @Operation(summary = "根据网站id获取栏目层级")
    @GetMapping("/getCategoriesAll")
    public Result<List<AgCategoryVO>> getCategoriesAll(
            @RequestParam Integer websiteId) {

        // 获取分页后的栏目数据
        return categoryService.getCategoriesAll(websiteId);
    }

    @Operation(summary = "根据网站id获取所有父栏目")
    @GetMapping("/categories/getParents")
    public Result<List<AgCategoryVO>> getParents(@RequestParam Integer websiteId, HttpServletRequest request) {
        if (websiteId == null) {
            return Result.error();
        } else {
            List<AgCategoryVO> agCategoryVO = categoryService.getParents(request,websiteId);
            return Result.ok(agCategoryVO);
        }
    }

    @Operation(summary = "根据父栏目id查询所有子栏目")
    @GetMapping("/getSubCategories")
    public Result<List<AgCategoryVO>> getSubCategories(@RequestParam Integer parentId, @RequestParam Integer type) {
        //根据父id查询父name
        List<AgCategoryVO> subCategories = categoryService.getSubCategories(parentId,type);
        return Result.ok(subCategories);
    }

    @Operation(summary = "新增父栏目")
    @PostMapping("/categories/parent")
    public Result<String> addParentCategory(@RequestBody AgCategoryVO categoryVO) {
        AgCategoryEntity entity = new AgCategoryEntity();
        BeanUtils.copyProperties(categoryVO, entity);
        entity.setParentId(0); // 父栏目 id 为 0
        entity.setDeleted(0);
        entity.setLevel(1);
        entity.setImageUrl(categoryVO.getImageUrl());
        entity.setCreateTime(new Date());
        entity.setApproveType("1");
        entity.setApproveState("1");
        int i = categoryService.addParentCategory(entity);
        if (i > 0) {
            return Result.ok("新增成功");
        } else {
            return Result.error();
        }
    }

    @Operation(summary = "根据父栏目id新增子栏目")
    @PostMapping("/categories/child")
    public Result<String> addChildCategory(@RequestBody AgCategoryVO categoryVO) {
        AgCategoryEntity entity = new AgCategoryEntity();
        BeanUtils.copyProperties(categoryVO, entity);
        int i = categoryService.addChildCategory(entity);
        if (i > 0) {
            return Result.ok();
        }else {
            return Result.error("当前父栏目已关联内容，无法新增子栏目");
        }
    }

    @Operation(summary = "修改父栏目")
    @PutMapping("/categories/parent/{categoryId}")
    public Result<Void> updateParentCategory(@PathVariable Long categoryId, @RequestBody AgCategoryVO categoryVO) {
        int i = categoryService.updateParentCategory(categoryId, categoryVO);
        if (i > 0) {
            return Result.ok();
        } else {
            return Result.error("栏目名称已存在，不能修改");
        }
    }

    @Operation(summary = "修改子栏目")
    @PutMapping("/child/{categoryId}")
    public Result<Void> updateChildCategory(@PathVariable Long categoryId, @RequestBody AgCategoryVO categoryVO) {
        int i = categoryService.updateChildCategory(categoryId, categoryVO);
        if (i > 0) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    @Operation(summary = "删除子栏目")
    @DeleteMapping("/child/{categoryId}")
    public Result<Void> deleteChildCategory(@PathVariable Long categoryId) {
        int i = categoryService.deleteChildCategory(categoryId);
        if (i > 0) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    @Operation(summary = "删除父栏目")
    @DeleteMapping("/parent/{categoryId}")
    public Result<Void> deleteParentCategory(@PathVariable Long categoryId) {
        int i = categoryService.deleteParentCategory(categoryId);
        if (i > 0) {
            // 删除成功
            return Result.ok();
        } else if (i == -1) {
            // 只能删除父栏目
            return Result.error("只能删除父栏目");
        } else if (i == -2) {
            // 该父栏目下有子栏目，不能删除
            return Result.error("该父栏目下有子栏目，不能删除");
        } else {
            // 其他未处理的错误
            return Result.error("删除失败");
        }
    }

    @Operation(summary = "新增或修改二级栏目图片")
    @PostMapping("/changeCategoryImage")
    public Result<String> changeCategoryImage(@RequestParam("categoryId") Long categoryId,
                                              @RequestParam("file") MultipartFile file) {
        // 1. 校验文件是否为空
        if (file.isEmpty()) {
            return Result.error("请选择需要上传的文件");
        }

        // 2. 校验文件类型
        String contentType = file.getContentType();
        String fileTypeCategory = null;
        if (contentType != null) {
            fileTypeCategory = getFileTypeCategory(contentType);
        }
        if (StringUtils.isEmpty(fileTypeCategory)) {
            return Result.error("不支持的文件类型");
        }

        try {
            // 3. 上传文件
            String path = storageService.getPath(file.getOriginalFilename());
            String url = storageService.upload(file.getBytes(), path);

            // 4. 更新数据库中的栏目图片字段
            // 假设你的表字段是 image_url，可以这样写：
            int rows = categoryService.updateCategoryImage(categoryId, url);
            if (rows > 0) {
                return Result.ok("上传成功");
            } else {
                return Result.error("栏目ID不存在或更新失败");
            }

        } catch (IOException e) {
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
    private String getFileTypeCategory(String contentType) {
        if (contentType.startsWith("image")) {
            return "image";

        }
        return null;
    }
}
